import clone from "clone";
import { v4 as uuidv4 } from "uuid";
import { DataSourceImp, DataSourceType, LowCodeImp } from "./type";
const lowCodeInstance = Symbol("lowCodeInstance");



export class DataSource implements DataSourceImp {
    private [lowCodeInstance]!: LowCodeImp;
    currentDataSource!: DataSourceType | null;
    constructor(lowcode?: LowCodeImp,) {
        if (lowcode) {
            this[lowCodeInstance] = <LowCodeImp>lowcode
        }
        this[lowCodeInstance] && this.init()
    }

    init() {
        this.currentDataSource = this[lowCodeInstance].dataSource[0]
        console.log('数据源初始化')
    }

    addDataSource(): DataSourceType {
        let dataSource = {
            key: uuidv4(),
            name: "测试数据源",
            url: "",
            method: "GET",
            auto: false,
        }
        this[lowCodeInstance].dataSource.push(dataSource)
        this.currentDataSource = dataSource
        return dataSource
    }

    removeDataSource(key: string): boolean {
        let index = this[lowCodeInstance].dataSource.findIndex(item => {
            return item.key == key
        })
        this[lowCodeInstance].dataSource.splice(index, 1)
        this.currentDataSource = null
        console.log('this.currentDataSource', this.currentDataSource)
        return true
    }

    copyDataSource(key: string): DataSourceType | null {
        let dataSource = this[lowCodeInstance].dataSource.find(item => {
            return item.key == key
        })
        let copydataSource;
        if (dataSource) {
            copydataSource = clone(dataSource)
            copydataSource.key = uuidv4()
            this[lowCodeInstance].dataSource.push(copydataSource)
            this.currentDataSource = copydataSource
            return copydataSource
        } else {
            return null
        }


    }

    updateDataSource(dataSource: DataSourceType): boolean {
        let index = this[lowCodeInstance].dataSource.findIndex(item => {
            return item.key == dataSource.key
        })
        this[lowCodeInstance].dataSource.splice(index, 1)
        this[lowCodeInstance].dataSource.splice(index, 0, dataSource)
        this.currentDataSource = dataSource
        return true
    }

}